<template>
  <view class="public-header" style="--header-height:6rem;">
    <view class="header-bar" :style="setStyle">
      <view class="left flex align-center header-bar-item">
        <view class="action flex align-center " @tap="backPage" v-if="isBack&&canBack">
          <text class="cuIcon-back"></text>
          <slot name="backText"></slot>
        </view>
        <view class="action flex align-center " @tap="backPage" v-else>
          <text class="cuIcon-homefill text-green"></text>
          <slot name="backText"></slot>
        </view>
        <text @click="backPage" class="padding-right title">{{title||''}}</text>
      </view>
      <view class="store-name header-bar-item" @touchend="isDoubleClick">
        <!-- 当前店铺名称 -->
        <text v-if="tenantInfo&&tenantInfo.tenant_name"> {{tenantInfo.tenant_name}}</text>
      </view>
      <view class="right header-bar-item">
        <image :src="menu.img" class="right-icon" mode="aspectFit" v-for="menu in menus" @click="onTab(menu.type,menu)">
        </image>
      </view>
    </view>
    <view class="slot">

    </view>
    <feature-menus ref="featureMenus"></feature-menus>
    <view class="custom-right-popup">
      <u-popup :show="showPopup" :round="20" mode="right" :overlay="true" :closeable="false" :closeOnClickOverlay="true"
        @close="close">
        <view class="mine-view" v-if="curPopup=='mine'">
          <view class="title">
            我的
          </view>
          <view class="tenant-name" v-if="tenantInfo&&tenantInfo.tenant_name">
            商户名：{{tenantInfo.tenant_name}}
          </view>
          <view class="user-card">
            <view class="user-card-left">
              <view class="name">
                {{loginUser.real_name}}
              </view>
              <view class="phone">
                {{loginUser.mobile}}
              </view>
            </view>
            <image :src="getImagePath(loginUser.signature)" mode="aspectFit" v-if="loginUser&&loginUser.signature"
              class="user-card-profile">
            </image>
            <image src="/static/images/profile.png" mode="aspectFit" class="user-card-profile" v-else></image>
          </view>
          <view class="list">
            <view class="list-item">
              <view class="flex align-center">
                <image src="/static/icons/version.png" class="icon" mode="aspectFit"></image>
                <text>当前版本</text>
              </view>
              <text>V2.4.28</text>
            </view>
            <view class="list-item">
              <view class="flex align-center">
                <image src="/static/icons/kefu.png" class="icon" mode="aspectFit"></image>
                <text>签约售后人员</text>
              </view>
              <text>-</text>
            </view>
            <view class="list-item" @click="checkUpdate">
              <view class="flex align-center">
                <image src="/static/icons/version.png" class="icon" mode="aspectFit"></image>
                <text>检查新版本</text>
              </view>
            </view>
          </view>
          <view class="flex justify-center flex-1 align-end">
            <button class="button lg margin-right line-white" @click="jjb">交接班</button>
            <button class="button lg" @click="logout">退出登录</button>
          </view>
        </view>
      </u-popup>
      <uni-popup ref="popupMsg" type="bottom">{{popupMsgText}}</uni-popup>
    </view>
    <movable-area class="movable-area"
      v-if="onSetting&&theLockScreenSettings&&enabledLock===true&&theLockScreenSettings.fastButton===true">
      <movable-view :x="x" :y="y" direction="all" @change="onMoveableViewChange">
        <view class="lock-screen-button">
          <text class="cuIcon-lock" v-if="onLockScreen"></text>
          <text class="cuIcon-unlock" v-else></text>
        </view>
      </movable-view>
    </movable-area>
    <view class="lock-screen-button fixed" :style="lockIconStyle"
      v-else-if="theLockScreenSettings&&enabledLock===true&&theLockScreenSettings.fastButton===true"
      @click="setLockState()">
      <text class="cuIcon-lock" v-if="onLockScreen"></text>
      <text class="cuIcon-unlock" v-else></text>
    </view>
    <view class="full-screen-lock" :class="{show:onLockScreen==true}" :style="setfullScreenLockStyle"
      @touchstart="startTouch" @touchend="endTouch" v-if="enabledLock===true">
      <view class="login-form" @touchstart.stop="" v-if="enabledPasswordLock===true">
        <view class="loading-box" :class="{show:loading===true}">
          <view class="cu-load loading"></view>
        </view>
        <view class="login-form-title">
          屏保解锁
        </view>
        <view class="input-box">
          <view class="input-item">
            <text class="cuIcon-mobile"></text>
            <input type="text" placeholder="请输入手机号" class="input" v-model="loginForm.user_no">
          </view>
          <view class="input-item">
            <text class="cuIcon-lock"></text>
            <input type="text" :password="!showPassword" placeholder="请输入密码" class="input" v-model="loginForm.pwd">
            <text class="cuIcon-attention uni-eye" :class="[!showPassword ? 'uni-eye-active' : '']"
              @click="changePassword"></text>
          </view>
        </view>
        <view class="button-bar">
          <button class="button lg round full" :class="{disabled:!loginForm.user_no||!loginForm.pwd}"
            @click="toLogin">确定</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  var timer = null
  import checkUpdate from '@/uni_modules/uni-upgrade-center-app/utils/check-update'
  export default {
    name: "public-header",
    props: {
      title: {
        type: String,
        default: ''
      },
      isBack: {
        type: [Boolean, String],
        default: true
      },
      bgColor: {
        type: String,
        default: ''
      },
      textColor: {
        type: String,
        default: ''
      },
      onSetting: {
        type: Boolean,
        default: false
      },
      backUrl: {
        type: String,
        default: ''
      },
      lockScreenSettings: {
        type: Object,
        default () {
          return this.$lockScreenSettings || null
        },
      }
    },
    data() {
      return {
        theLockScreenSettings: null,
        sysInfo: {

        },
        canBack: false,
        loading: false,
        showPassword: false,
        loginForm: {
          tenant: null,
          user_no: "",
          pwd: ""
        },
        touchData: {
          clientX: '',
          clientY: ''
        },
        touchNum: 0,
        curTime: "",
        curDate: "",
        x: 100,
        y: 200,
        old: {
          x: 0,
          y: 0
        },
        showPopup: false,
        onTouch: false,
        curPopup: "",
        menus: [{
            name: '功能菜单',
            img: require('@/static/icons/menus.png'),
            type: 'feature'
          },
          {
            name: '订单',
            img: require('@/static/icons/order.png'),
            type: 'order',

            target: "/pages/main/orderList/orderList?srv=srvretail_store_order_select&pageType=listAndDetail&&listLayout=listAndDetail&title=销售管理"
          },
          {
            name: '排行',
            img: require('@/static/icons/rank.png'),
            type: 'rank',

          },
          {
            name: '打印机',
            img: require('@/static/icons/dyj.png'),
            type: 'printer'
          },
          {
            name: '我的',
            img: require('@/static/icons/wd.png'),
            type: 'mine'
          }
        ]
      };
    },
    mounted() {
      // if(!this.theLockScreenSettings){
      this.theLockScreenSettings = this.$lockScreenSettings || {}
      if (this.theLockScreenSettings?.fastButtonX && this.theLockScreenSettings?.fastButtonY) {
        this.x = this.theLockScreenSettings?.fastButtonX
        this.y = this.theLockScreenSettings?.fastButtonY
      }
      // }

      this.sysInfo = uni.getSystemInfoSync()

      setTimeout(() => {
        const pages = getCurrentPages()
        if (Array.isArray(pages) && pages.length > 1) {
          this.canBack = true
        } else {
          this.canBack = false
        }
      }, 1000)
    },
    beforeDestroy() {
      clearInterval(timer)
    },
    computed: {
      // canBack() {
      // 	const pages = getCurrentPages()
      // 	if (Array.isArray(pages) && pages.length > 1) {
      // 		return true
      // 	} else {
      // 		return false
      // 	}
      // },
      enabledPasswordLock() {
        return this.theLockScreenSettings?.lockWay === '密码解锁'
      },
      enabledLock() {
        return this.theLockScreenSettings?.enabled === true
      },
      setfullScreenLockStyle() {
        let img = this.theLockScreenSettings?.imgUrl || '/static/images/lockScreen.png'
        if (img) {
          return `background-image:url(${img});`
        }
      },
      lockIconStyle() {
        return `top:calc(${this.theLockScreenSettings?.fastButtonY}px + 6rem);left:${this.theLockScreenSettings?.fastButtonX}px;`
      },
      fastButton() {
        return this.theLockScreenSettings?.fastButton === true
      },
      // lockScreenSettings() {
      //   return this.$store.state.$lockScreenSettings
      // },
      setStyle() {
        let style = ''
        if (this.bgColor) {
          style += `background-color:${this.bgColor};`
        }
        if (this.textColor) {
          style += `color:${this.textColor};`
        }
        return style
      },
      popupMsgText() {
        let msg = this.msgLog || ""
        return msg
      }
    },
    watch: {
      theLockScreenSettings: {
        deep: true,
        immediate: true,
        handler(newValue, oldValue) {
          console.log(newValue, ',theLockScreenSettings');
        }
      },
      $lockScreenSettings: {
        deep: true,
        immediate: true,
        handler(newValue, oldValue) {
          if (newValue) {
            console.log(newValue);
            this.theLockScreenSettings = newValue
          }
        }
      },
      lockScreenSettings: {
        deep: true,
        immediate: true,
        handler(newValue, oldValue) {
          if (newValue) {
            console.log(newValue);
            this.theLockScreenSettings = newValue
          }
          if (newValue?.fastButton === true) {

          }
        }
      }
    },
    methods: {
      checkUpdate() {
        uni.showLoading({
          title: '版本检测中...'
        })
        this.sysInfo = uni.getSystemInfoSync()
        checkUpdate().then(res => {
          uni.hideLoading()
          // console.log(JSON.stringify(res));
          if (res?.result.code === 0) {
            uni.showToast({
              title: res?.result?.message,
              icon: 'none'
            })
          }
        }).catch((err) => {
          console.log(err);
          uni.showToast({
            title: '当前已经是最新版本',
            icon: 'none'
          })
        })
      },
      jjb() {
        if (!this.menuAuth['bxretail_aio_change_shifts']) {
          uni.showToast({
            title: '当前帐号没有交接班权限！',
            icon: 'none'
          })
          return
        }
        // 跳转到交接班
        uni.redirectTo({
          url: '/pages/main/setup/handovermgt/index?title=交接班'
        })
      },
      changePassword() {
        this.showPassword = !this.showPassword
      },
      toLogin() {
        if (!this.loginForm.user_no) {
          uni.showToast({
            title: '请输入登录账号',
            icon: 'none'
          })
          return
        }
        if (!this.loginForm.pwd) {
          uni.showToast({
            title: '请输入密码',
            icon: 'none'
          })
          return
        }
        this.accountLogin()
      },
      async accountLogin() {
        if (this.loginUser?.tenant) {
          this.loginForm.tenant = this.loginUser?.tenant
        }
        const req = [{
          "serviceName": "srvuser_login",
          "data": [{
            "user_no": this.loginForm.user_no,
            "pwd": this.loginForm.pwd,
            'tenant': this.loginForm?.tenant || null,
            "terminal_type": "mt",
          }]
        }]
        const url = `/sso/operate/srvuser_login`
        this.loading = true
        const res = await this.$http.post(url, req)
        this.loading = false
        if (res?.data?.state === 'SUCCESS') {
          this.$store.commit('SET_LOCK_STATE', !this.onLockScreen)
        } else {
          uni.showToast({
            title: res?.data?.resultMessage,
            icon: 'none'
          })
        }

      },
      /**
       * @description 检测双击
       * 300毫秒内点击两次则判定为双击
       */
      isDoubleClick(e) {
        this.touchNum++
        setTimeout(() => {
          if (this.touchNum == 1) {
            console.log('单击')
          }
          if (this.touchNum >= 2) {
            console.log('双击')
            if (this.theLockScreenSettings?.lockWay === '活动解锁') {
              this.setLockState()
            }
          }
          this.touchNum = 0
        }, 300)
      },
      startTouch(e) {
        this.touchData.clientX = e.changedTouches[0].clientX;
        this.touchData.clientY = e.changedTouches[0].clientY;
      },
      /**
       * @description 检测滑动方向
       * 50为安全距离 滑动距离小于50则不触发
       */
      endTouch(e) {
        this.isDoubleClick()
        const subX = e.changedTouches[0].clientX - this.touchData.clientX;
        const subY = e.changedTouches[0].clientY - this.touchData.clientY;

        if (subY > 50 || subY < -50) {
          console.log('上下滑', subY)
          if (subY < -50) {
            if (this.theLockScreenSettings?.lockWay === '活动解锁') {
              this.setLockState()
            }
          }
        } else {
          if (subX > 50) {
            console.log('右滑')
          } else if (subX < -50) {
            console.log('左滑')
          } else {
            console.log('无效')
          }
        }
      },
      setLockState() {
        let state = !this.onLockScreen
        this.$store.commit('SET_LOCK_STATE', state)
      },
      ontouchstart() {
        this.onTouch = true
      },
      ontouchend() {
        this.onTouch = false
      },
      setFloatButtonXY() {

      },
      setLockScreenSetting(lockScreenSettings) {
        // this.$store.commit('SET_LOCK_SCREEN', lockScreenSettings)
        this.$emit('set-lock', lockScreenSettings)
      },
      onMoveableViewChange(e) {
        this.old.x = e.detail.x
        this.old.y = e.detail.y
        let lockScreenSettings = this.theLockScreenSettings;
        lockScreenSettings.fastButtonX = e.detail.x
        lockScreenSettings.fastButtonY = e.detail.y
        // this.setLockScreenSetting(lockScreenSettings)
        // uni.$u.throttle(this.setLockScreenSetting(), 500)
        uni.$u.debounce(this.setLockScreenSetting(lockScreenSettings), 1000)
      },
      logout(clear) {
        if (clear === true) {
          uni.clearStorage()
        }
        this.close()
        this.curPopup = ''
        uni.showModal({
          title: '提示',
          content: '是否退出登录',
          success: (res) => {
            if (res.confirm) {
              let keys = ['$bx_auth_ticket', '$goodsList', '$loginUser', '$classifyList', '$memberList',
                '$staffList', '$curAssistant', '$curMember', '$memberSetup', '$srvCol', '$userMenuList'
              ]
              keys.forEach(key => {
                this.$store.commit('SET_STATE', {
                  key: key,
                  value: key && key.indexOf('ist') !== -1 ? [] : null
                })
              })
              // this.$store.commit('SET_TICKET', null)
              this.$store.commit('SET_LOGIN_STATE', false)
              uni.reLaunch({
                url: '/pages/main/login/login'
              })
            } else {
              uni.showToast({
                title: '用户点击了取消',
                icon: 'none'
              })
            }
          }
        })

      },
      close() {
        this.showPopup = false
      },
      onTab(e, menu) {
        switch (e) {
          case 'feature':
            if (!this.menuAuth['bxretail_aio_function_page']) {
              uni.showToast({
                title: '当前帐号没有访问权限!',
                icon: 'none'
              })
              return
            }
            this.$refs?.featureMenus?.open?.()
            break;
          case 'order':
            if (!this.menuAuth['bxretail_aio_sale_manage']) {
              uni.showToast({
                title: '当前帐号没有访问权限!',
                icon: 'none'
              })
              return
            }
            uni.redirectTo({
              url: menu.target
            })
            break;
          case 'rank':
            if (!this.menuAuth['bxretail_aio_report_overview']) {
              uni.showToast({
                title: '当前帐号没有访问权限!',
                icon: 'none'
              })
              return
            }
            uni.redirectTo({
              url: '/pages/main/report/index'
            })
            break;
          case 'printer':
            if (!this.menuAuth['bxretail_aio_cloud_printing']) {
              uni.showToast({
                title: '当前帐号没有访问权限!',
                icon: 'none'
              })
              return
            }
            uni.redirectTo({
              url: '/pages/main/setup/cloudPrint/index?title=云打印设备管理'
            })
            break;
          case 'mine':
            this.showPopup = true
            this.curPopup = 'mine'
            break;
        }
      },
      backPage(e) {
        if (this.isBack && this.canBack) {
          uni.navigateBack({
            delta: 1
          });
        } else {
          uni.reLaunch({
            url: '/pages/main/cash/cash'
          })
        }
      }
    },
  }
</script>

<style lang="scss">
  .slot {
    height: 6rem;
  }

  .title {
    height: 6rem;
    line-height: 6rem;
  }

  .full-screen-layer {
    width: 100vw;
    height: 100vh;
    position: fixed;
    left: 0;
    top: 0;
    // background-color: rgba(0, 0, 0, 0.2);
  }

  .full-screen-lock {
    width: 100vw;
    height: 100vh;
    position: fixed;
    left: 0;
    top: -100vh;
    background-color: #28322B;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    transition: top cubic-bezier(1, -0.31, 0.54, 1.21) 0.5s;
    z-index: 9999999999;
    border-radius: 0;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    color: #fff;

    .center {
      background-color: rgba(0, 0, 0, 0.2);
      padding: 5rem;
      border-radius: 2rem;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      overflow: hidden;
    }

    .time {
      display: flex;
      font-size: 20rem;
      line-height: 30rem;
      font-weight: 700;
    }

    .date {
      font-size: 10rem;
      line-height: 20rem;
      margin-top: 2rem;
      font-weight: 500;
    }

    &.show {
      top: 0;
    }

  }

  .lock-screen-button {
    width: 10rem;
    height: 10rem;
    background: rgba(0, 0, 0, 0.1);
    border-radius: 50%;
    font-size: 5rem;
    line-height: 10rem;
    text-align: center;

    &.fixed {
      position: fixed;
      z-index: 9999;

      &:active {
        background-color: rgba(0, 0, 0, 0.2);
      }
    }
  }

  .public-header {
    position: relative;
  }

  .header-bar {
    z-index: 9;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    color: #fff;
    background-color: #28322B;
    font-size: $retail-font-size-sm;
    padding: 0 4rem 0 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    // height: 5.6vh;
    height: 6rem;

    // padding-top: var(--status-bar-height); //状态栏高度
    &-item {
      flex: 1;
      text-align: center;
    }

    .left {
      .action {
        font-size: 3rem;
        padding: 0 2rem;
        height: 6rem;

        &:active {
          opacity: 0.9;
          background-color: rgba(255, 255, 255, 0.1);
        }
      }
    }

    .right {
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }

  .right-icon {
    margin-left: 5rem;
    width: 3.2rem;
    height: 3.2rem;

    &:active {
      opacity: 0.6;
      transform: translate(1px, 1px);
    }
  }

  .mine-view {
    display: flex;
    flex-direction: column;
    padding: 3rem 3rem 4rem;
    width: 52.5rem;
    height: 100%;

    .title {
      font-size: 3rem;
      font-weight: 700;
      border-left: 4px solid $retail-color-primary;
      padding: 0 1.5rem;
    }

    .tenant-name {
      font-size: 2rem;
      margin-top: 1.7rem;
    }

    .list {
      &-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 2.4rem;
        font-size: 2rem;

        .icon {
          width: 3.2rem;
          height: 3.2rem;
          margin-right: 1.8rem;
        }
      }
    }

    .user-card {
      display: flex;
      background-color: #F5F5F5;
      border-radius: 1rem;
      align-items: center;
      padding: 1.5rem 1.8rem;
      margin: 1.8rem 0;

      &-left {
        flex: 1;

        .name {
          font-size: 3rem;
          font-weight: 700;
          line-height: 5rem;
          margin-bottom: .7rem;
        }

        .phone {
          font-size: 2rem;
        }
      }

      &-profile {
        width: 8rem;
        height: 8rem;
        border-radius: 50%;
      }
    }
  }

  .movable-area {
    // width: 90vw;
    // height: 80vh;
    // height: calc(100vh - var(--header-height));
    position: fixed;
    top: var(--header-height);
    left: 0;
    z-index: 100;
    width: 100vw;
    height: calc(100vh - var(--header-height) - 10rem);
    pointer-events: none;

    .lock-screen-button {
      pointer-events: all;
    }
  }

  .login-form {
    background-color: #fff;
    padding: 4rem 5rem;
    border-radius: 1rem;
    position: relative;

    .loading-box {
      position: absolute;
      display: none;
      width: 100%;
      height: 100%;
      left: 0;
      top: 0;
      border-radius: 1rem;

      &.show {
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 999;
        color: #333;
        background-color: rgba(255, 255, 255, 0.5);
        font-size: 3.4rem;
      }
    }

    &-title {
      font-size: 2.4rem;
      font-weight: bold;
      color: #333;
      text-align: center;
      padding: 3rem;
    }

    .button-bar {
      margin-top: 4rem;
    }

    .input-box {
      flex: 1;

      .input-item {
        display: flex;
        align-items: center;
        width: 52.4rem;
        height: 8rem;
        margin-top: 2rem;
        border-radius: 1.2rem;
        border: 1px solid #E5E5E5;
        font-size: 4rem;
        padding: 0 3rem;
        color: $retail-color-primary;

        .label {
          font-size: $retail-font-size-sm;
          color: #333;
        }

        .input {
          margin-left: 3rem;
          font-size: $retail-font-size-sm;
          flex: 1;
          color: #666;

          &.text-right {
            text-align: right;
          }
        }
      }
    }
  }

  .custom-right-popup {
    ::v-deep .u-popup {
      z-index: 99999999;
    }
  }
</style>
